import React, { Component, ComponentClass } from 'react';
import Taro from '@tarojs/taro';
import Skeleton from 'taro-skeleton'
import {connect} from 'react-redux'
import {View, Navigator, Image, Block} from '@tarojs/components'
import LocalGoodsBox from '../components/local-life-goods/big-goods-box'
import {
  CityLocation as CityLocationType,
  IndexCategory,
  ScenicIndexPageData,
  Good
} from '../../utils/server.interface'
import './index.scss'
import {platform} from '../../utils/platform-settting.service'
import {http} from '../../utils/http'
import {
  IDENTITY,
  RESOURCE_URL,
  LIAN_QUERY_PRODUCT_LIST,
  LIAN_GET_LOCATION_LIST,
  SCAN_BIND_SELLER
} from '../../constants/api'
import CityLocation from '../../components/city-location/city-location'
import {getHeadTop, GetRequest, vcmonitor} from '../../utils/tools'
import {user} from '../../utils/user.service'
import SupportBar from '../../components/support-bar/support-bar'
import {newHttp} from "../../utils/request";
import {h5Wx} from "../../utils/h5.service";
import GzhAuth from "../../components/gzh-auth/gzh-auth"

type PageStateProps = {
  location: CityLocationType
}
type PageDispatchProps = {}
type PageOwnProps = {}
type PageState = {
  loadMoreStatus: 'more' | 'noMore' | 'loading'
  goods: Good[]
  categorys: IndexCategory[]
  pageData: ScenicIndexPageData
  showLoading: boolean
  pageshowLoading: boolean
  localTitle: string
  userIdentity: any
  lainLocation: any
}
type IProps = PageStateProps & PageDispatchProps & PageOwnProps

interface Index {
  props: IProps
}

@connect(({location}) => ({
  location
}), () => ({}))

class Index extends Component {
  state:
    { lainLocation: {}; localTitle: string; goods: any[]; pageshowLoading: boolean; loadMoreStatus: string; pageData: { headBg: string; adImg: { img: string; url: string }; pageTitle: string; menus: any[]; recommondGoods: any[] }; userIdentity: any[]; showLoading: boolean } = {
    loadMoreStatus: 'loading',
    goods: [],
    pageData: {
      headBg: "https://resource.ivcheng.com/resources/system/img/scenic.jpg",
      pageTitle: "景点详情",
      menus: [],
      adImg: {
        img: "",
        url: ""
      },
      recommondGoods: []
    },
    showLoading: true,
    pageshowLoading: true,
    localTitle: '',
    userIdentity: [],
    lainLocation: {}
  }
  page = 1
  shareParams = ''

  async UNSAFE_componentWillMount() {
    if(await user.checkLogin()) {
      this.setState({userIdentity: await http.get(IDENTITY, {})})
    }
    this.setState({
      pageshowLoading: false,
      showLoading: false,
    })
    this.shareParams = await user.getSellerParams()
    if (process.env.TARO_ENV === 'h5') {
      await h5Wx.getConfig()
      const shareData = {
        title: platform.info.platformName,
        desc: '本地生活',
        link: window.location.origin + '/common/local-life/index?' + this.shareParams,
        imgUrl: platform.info.platformLogo
      }
      await h5Wx.share(shareData)
    }
    const bindSellerIds = Taro.getCurrentInstance().router.params.bindSellerId || ''
    const tempSellerIds = Taro.getCurrentInstance().router.params.tempSellerId || ''
    if ((bindSellerIds || tempSellerIds) && process.env.DISTINGUISH_IDENTITY) {
      http.HPost(SCAN_BIND_SELLER, { temp_seller_id: tempSellerIds, refer_seller_id: bindSellerIds });
    }
  }

  async componentDidShow() {
    vcmonitor(this)
    this.page = 1
    const goods = await this.getGoods(this.page)
    let lainLocation = Taro.getStorageSync('lianCity')
    if (!Taro.getStorageSync('lianCity') && this.props.location.area_name !== '全国') {
      const allCity = await newHttp.catchGet(LIAN_GET_LOCATION_LIST, {})
      const cityData = allCity.data
      const areaName = this.props.location.area_name.substr(0, 2)
      const index = cityData.findIndex(item => { return item.cityName.startsWith(areaName) })
      if (index > -1) {
        const indexData = cityData[index]
        lainLocation = { area_name:indexData.cityName,region_id:indexData.id }
        Taro.setStorageSync('lianCity', lainLocation)
      }
    }
    this.setState({
      goods,
      lainLocation
    })
  }

  onShareAppMessage() {
    return {
      title: platform.info.platformName,
      path: '/common/local-life/index?' + this.shareParams + `&sKey=${Taro.getStorageSync('sKey' || '')}`
    }
  }

  onShareTimeline() {
    return {
      title: platform.info.platformName,
      query: this.shareParams + `&sKey=${Taro.getStorageSync('sKey' || '')}`
    }
  }

  async getGoods(page = 1) {
    const goodsData = await newHttp.catchGet(LIAN_QUERY_PRODUCT_LIST, {
      city: Taro.getStorageSync('lianCity') ? Taro.getStorageSync('lianCity').area_name : Taro.getStorageSync('city') ? Taro.getStorageSync('city').area_name.replace('市', '') : '烟台',
      pageIndex: page,
      pageSize: 10,
      title: this.state.localTitle
    })
    if (goodsData.data) {
      if (goodsData.data.length < 10) {
        this.setState({loadMoreStatus: 'noMore'})
      } else {
        this.setState({loadMoreStatus: 'more'})
      }
      return goodsData.data
    } else {
      this.setState({loadMoreStatus: 'noMore'})
      return []
    }
  }

  async searchClick() {
    this.page = 1
    this.setState({loadMoreStatus: 'loading', goods: []}, async () => {
      const goods = await this.getGoods(this.page)
      this.setState({goods})
    })
  }

  searchClear() {
    this.page = 1
    this.setState({loadMoreStatus: 'loading', goods: []}, async () => {
      const goods = await this.getGoods(this.page)
      this.setState({goods})
    })
  }

  async onReachBottom() {
    if (this.state.loadMoreStatus != 'noMore') {
      this.setState({loadMoreStatus: 'loading'})
      const old = this.state.goods
      this.page++
      const newData = await this.getGoods(this.page)
      this.setState({goods: [...old, ...newData]})
    }
  }

  onChange(value) {
    this.setState({localTitle: value})
  }

  async callbackonActionClick() {
    this.setState({goods: []}, async () => {
      const newData = await this.getGoods(this.page)
      this.setState({goods: newData})
    })
  }

  render() {
    const {lainLocation, userIdentity, goods, pageData, showLoading, pageshowLoading} = this.state
    return (
      <View className='scenic-root' id='root'>
        <GzhAuth />
        <Skeleton title className='paddingNone' loading={showLoading} titleWidth='100%' rowHeight='75px'>
          <Block>
            <View className='local-life-head'>
              <View className='search-bar'>
                <CityLocation locations={lainLocation} type='lianlian' local='true'
                  onCallBackActionClick={this.callbackonActionClick.bind(this)}
                  onCallBackParent={this.onChange.bind(this)}
                />
              </View>
            </View>
          </Block>
        </Skeleton>
        <View className='zoom'>
          {pageData.adImg.img && <Navigator className='ad-module' url={pageData.adImg.url}>
            <Image className='img' src={pageData.adImg.img} mode='aspectFill' />
          </Navigator>}
          <Skeleton title loading={pageshowLoading} row={3} rowHeight={220}>
            <Block>
              <View className='bottom-goods'>
                <View className='local-list'>
                  <View className='top-name'>精选推荐</View>
                  <View>
                    <View />
                  </View>
                </View>
                <LocalGoodsBox isSeller={userIdentity.isSeller} data={goods} />
                {goods && goods.length == 0 &&
                <View className='listNull'>
                  <Image src={`${RESOURCE_URL}resources/images/shopnull.png`} mode='widthFix' />
                  <View className='text'>什么都没有,去看看别的吧~</View>
                </View>
                }
              </View>
            </Block>
          </Skeleton>
        </View>
        <SupportBar />
      </View>
    )
  }
}

export default Index as ComponentClass<PageOwnProps, PageState>
